@tool
extends  EditorProperty

const ATTRIBUTE_EDITOR_ROW_COMP = preload("res://addons/gameplay-ability-system/Scripts/Inspector/components/attibute_comp/AttributeEditorRowComp.tscn")

var scrollbar := VBoxContainer.new()


func _ready() -> void:
	add_child(scrollbar)
	var attribute_set_obj = get_edited_object() as AttributeSet
	if attribute_set_obj:
		draw_attributes(attribute_set_obj.attributes)

# 重新列出所有属性
func draw_attributes(attributes:Array[Attribute]):
	for child in scrollbar.get_children():
		child.queue_free()
	
	var attribute_set = get_edited_object() as AttributeSet
	var attribute_dictionary = attribute_set.attribute_dictionary
	
	for attribute in attributes:
		var attribute_row = ATTRIBUTE_EDITOR_ROW_COMP.instantiate()
		attribute_row.attribute = attribute
		
		if attribute_dictionary:
			attribute_row.attribute_dictionary = attribute_dictionary.attirbute_list
		
		attribute_row.remove_attribute.connect(_on_remove_attribute)
		
		scrollbar.add_child(attribute_row)
		
	var new_attribute_btn = Button.new()
	new_attribute_btn.pressed.connect(_on_add_attribute_pressed)
	new_attribute_btn.text = "添加 Attribute"
	scrollbar.add_child(new_attribute_btn)


# 添加Attribute的按钮被点击
func _on_add_attribute_pressed():
	var attribute_set = get_edited_object() as AttributeSet
	attribute_set.attributes.append(Attribute.new())
	# 修改资源后调用：
	save_attribute_set()
	draw_attributes(attribute_set.attributes)


# 移除Attribute的按钮被点击
func _on_remove_attribute(attribtue:Attribute):
	var attribute_set = get_edited_object() as AttributeSet
	attribute_set.attributes.erase(attribtue)
	save_attribute_set()
	draw_attributes(attribute_set.attributes)

# 资源保存
func save_attribute_set():
	emit_changed(get_edited_property(), get_edited_object().attributes)
	get_edited_object().notify_property_list_changed()
